package com.niuwa.p2p.action;
import java.io.File;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.InterceptorRefs;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.json.annotations.JSON;
import org.springframework.beans.factory.annotation.Autowired;

import com.niuwa.p2p.service.filesystem.FileSystem;
import com.opensymphony.xwork2.ActionSupport;

/**
 * 
 * 单文件上传
 * 
 * @author jishengjun
 * 如果office文件上传错误，可放宽到如下条件，再在逻辑里判断后缀名
 * application/octet-stream ： .dll,.a,.bin,.exe,.so
 * application/x-zip-compressed： zip
 */
@ParentPackage(value="json-default")
@InterceptorRefs(value = { 
		@InterceptorRef(value="fileUpload",params={"allowedTypes","image/bmp,image/png,image/gif,image/jpeg,text/xml,text/plain,"
				+ "application/vnd.ms-excel,application/excel,application/msword,"
				+ "application/vnd.ms-powerpoint,application/pdf,"  
				+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document," 
                + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,"
                + "application/vnd.openxmlformats-officedocument.presentationml.presentation,application/octet-stream,application/x-zip-compressed","maximumSize","2097152"}),
		@InterceptorRef(value = "defaultStack")		
})
public class AjaxFileUploadAction extends ActionSupport {    
    /**
	 * 
	 */
	private static final long serialVersionUID = -3264533716348991025L;
	
	//上传的文件
	private File file;
	
	//文件名称
    private String fileFileName;
    
    //文件类型
    private String fileContentType; 
    
	// 是否上传成功
	private boolean success;
	
	// 文件ID
	private String fileID;

	// 文件系统
	@Autowired
	private FileSystem fileSystem;
	
	public String getFileID() {
		return fileID;
	}

	public void setFileID(String fileID) {
		this.fileID = fileID;
	}
	
	// 文件不实施序列化，不计入json对象
	@JSON(serialize=false)
	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}

	public String getFileFileName() {
		return fileFileName;
	}


	public void setFileFileName(String fileFileName) {
		this.fileFileName = fileFileName;
	}

	public String getFileContentType() {
		return fileContentType;
	}

	public void setFileContentType(String fileContentType) {
		this.fileContentType = fileContentType;
	}
    
    public boolean isSuccess() {
		return success;
	}

	public void setSuccess(boolean success) {
		this.success = success;
	}

	private String message = "你已成功上传文件";
    
    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
    
    @Action(value="ajaxFileUpload", 
    	results={@Result(type="json", name="success", params={"contentType", "text/html"}), 
    			@Result(type="json", name="input", params={"contentType", "text/html"}), 
    			@Result(type="json", name="error", params={"contentType", "text/html"})})
    public String ajaxFileUpload() throws Exception {
    	
    	// 判断是否是空文件
    	if (file == null || file.length() <=0) {
    		success = false;
    		message = "不能上传空文件";
	       	return ERROR;
    	}
    	
        try {        	
        	File reNameFile = new File (file.getParent(),fileFileName);
        	FileUtils.copyFile(file, reNameFile);
	        String storefileID = fileSystem.savePrivateFile(reNameFile);
	        setFileID(storefileID);
	        reNameFile.delete();
        } catch(Exception ioe) {
	        success =false;
	       	message = "对不起,文件上传失败了!!!!";
	       	return ERROR;
       } 
       success = true;
       return SUCCESS;
    }
   
    
    /** 
     * 从服务器上 删除文件 
     * @param fileName 文件名 
     * @return true: 从服务器上删除成功   false:否则失败 
     */
    @Action(value="delFile", 
        	results={@Result(type="json", name="success"),         			 
        			 @Result(type="json", name="error")})
    public String delFile(){  

        try { 
    		fileSystem.deleteFile(fileID);
        } catch(Exception ioe) {
	        success =false;
	       	message = "对不起,删除文件失败";
	       	return ERROR;
        }
        success = true;
       	message = "删除文件成功";
       	return ERROR;
    }  
    
    @Override  
    public void addActionError(String anErrorMessage) {  
        if (anErrorMessage.startsWith("Request exceeded allowed size limit!")) { 
        	// 处理上传文件过大导致系统错误（实质：防止恶意上传）
            success =false;
            message = anErrorMessage;
            super.addActionError(anErrorMessage);
        } else {
        	// 按原来的方法处理  
            super.addActionError(anErrorMessage);
        }  
    }
    
    @Override
    public void addFieldError(String fieldName, String errorMessage) { 
    	 if (errorMessage.startsWith("上传文件 ")) { 
    		 // 处理拦截器文件过大
             success =false;
             message = errorMessage;
             super.addFieldError(fieldName, errorMessage); 
         } else if (errorMessage.startsWith("不支持上传的类型")) {
        	 // 处理拦截器上传类型不支持
             success =false;
             message = errorMessage;
             super.addFieldError(fieldName, errorMessage); 
         } else {
        	 // 按原来的方法处理  
        	 super.addFieldError(fieldName, errorMessage); 
         }
    }
    
}